package club.pchome.controller;

import club.pchome.dto.Result;
import club.pchome.ex.ServiceException;
import club.pchome.ex.code.BaseResponseCode;
import club.pchome.utils.DateUtil;
import club.pchome.utils.ExecuJs;
import club.pchome.utils.IpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.mail.MailUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

/**
 * @author Watler
 */
@Api( tags = {"公共处理类"})
@RestController
@RequestMapping("/public")
public class CommonController extends BaseController {


    @GetMapping("/regImgCode")
    public void authImage(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(defaultValue = "120") int width ,
                          @RequestParam(defaultValue = "40") int height
    ) throws IOException {

        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, 4, 20);
        String uuid = IdUtil.simpleUUID();

        IpUtil ipUtil = new IpUtil();
        String ip = ipUtil.getIpAddr(request);
        //验证码存入redis
        redisUtil.set(uuid , captcha.getCode() , 60);
//        logger.info("CaptchaCode for key : {}", uuid);

        //将验证码key，及验证码的图片返回
        Cookie cookie = new Cookie("CAPTCHA", uuid);
        //如果前后端分离,切不同域名端口,这里一定要这样设置
        cookie.setPath("/");
        response.addCookie(cookie);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();
        captcha.write(os);
        os.flush();
        os.close();
    }

    @RequestMapping("/_stm")
    public Result<String> verifyCode(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        Cookie[] cookies = request.getCookies();
        String token = null;
        //遍历所有的cookie,然后根据cookie的key值来获取value值
        if (cookies!=null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getValue());
                if (cookie.getName().equals("ACCESS_TOKEN")) {
                    token = cookie.getValue();
                }
            }

            String ACCESS_TOKEN = "ACCESS_TOKEN:" + token;
            boolean b = redisUtil.hasKey(ACCESS_TOKEN);
            if(!b){
                System.out.println(b);
                throw new ServiceException(BaseResponseCode.TOKEN_EXPIRE_ERROR);
            }

            String accessToken = redisUtil.get("ACCESS_TOKEN:" + token).toString();
            return Result.initSuccessResult("成功");
        }
//        System.out.println(isTokenExpired("100af57743c343729aa707ad38bd22bf"));
        return Result.initSuccessResult(""+System.currentTimeMillis());
    }

    private static int num = 1;
    @GetMapping("/execuJs")
    public Result<String> execuJs(String url){
        String ua = request.getHeader("User-Agent");
        logger.info("设备信息:{} , 第{}次使用" , ua , num);
        String c = ExecuJs.execuJs(url);
        num++;
        return Result.initSuccessResult(c);
    }

    /**
     * 发送邮件
     * @param to
     * @param subject
     * @param content
     * @param isHtml
     */
    @ApiOperation(value = "发送邮件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "to", value = "账号(手机号)", required = true),
            @ApiImplicitParam(name = "subject", example = "545163269@qq.com", value = "标题", required = true),
            @ApiImplicitParam(name = "content", value = "内容", required = true),
            @ApiImplicitParam(name = "isHtml", value = "是否为HTML", required = false),
    })
    @GetMapping("/sendMail")
    public void sendMail(String to, String subject, String content, Boolean isHtml){
        logger.info("发送邮件");
        if(isHtml == null){
            isHtml = false;
        }else {
            isHtml = true;
        }
        content = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>邮件提醒</title>\n" +
                "    　　\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +
                "    <!--<script type=\"text/javascript\">-->\n" +
                "        <!--//        var para = function () {-->\n" +
                "        <!--//        }-->\n" +
                "        <!--var url = document.location.toString();-->\n" +
                "        <!--var arrUrl = url.split(\"?\");-->\n" +
                "        <!--var para = arrUrl[1];-->\n" +
                "        <!--alert('===='+url);-->\n" +
                "    <!--</script>-->\n" +
                "</head>\n" +
                "\n" +
                "<body style=\"margin: 0; padding: 0;\">\n" +
                "\n" +
                "<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse: collapse;\">\n" +
                "\n" +
                "    　\n" +
                "    <tr>\n" +
                "        <td>\n" +
                "            <div style=\"margin: 20px;text-align: center;margin-top: 50px\">\n" +
                "                <img src=\"https://cxbres.oss-cn-beijing.aliyuncs.com/CTSP/mail/header/20180904115147.png\" border=\"0\" style=\"display:block;width: 100%;height: 100%\">\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "\n" +
                "    <tr>\n" +
                "        <td>\n" +
                "            <div style=\"border: #36649d 1px dashed;margin: 30px;padding: 20px\">\n" +
                "                <label style=\"font-size: 22px;color: #36649d;font-weight: bold\">恭喜您，注册成功！</label>\n" +
                "                <p style=\"font-size: 16px\">亲爱的&nbsp;<label style=\"font-weight: bold\"> XXX先生/女士</label>&nbsp; 您好！欢迎加入xxx。\n" +
                "                </p>\n" +
                "                <p style=\"font-size: 16px\">您已于"+ DateUtil.YYYY_MM_DD_MM_HH_SS.format(new Date()) +"充值成功，希望更好的为您服务！</p>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "    　\n" +
                "    <tr>\n" +
                "        <td>\n" +
                "            <div style=\"margin: 40px\">\n" +
                "                <p style=\"font-size: 16px\">xxx管理团队</p>\n" +
                "                <p style=\"color:red;font-size: 14px \">（这是一封自动发送的邮件，请勿回复。）</p>\n" +
                "\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "\n" +
                "    <!--<tr>-->\n" +
                "        <!--<td>-->\n" +
                "            <!--<div style=\"font-size:14px;margin-left: 30px;margin-right: 30px;padding: 20px\">-->\n" +
                "                <!--<img src=\"tile-wide.png\" alt=\"\" style=\"width: 100px;height: 100px\"/>-->\n" +
                "                <!--<label style=\"font-size: 12px;display:block;\"> 关注公众号了解更多</label>-->\n" +
                "                <!--&lt;!&ndash;<p style=\"font-size: 12px\">&ndash;&gt;-->\n" +
                "                    <!--&lt;!&ndash;如有任何问题，可以与我们联系，我们将尽快为你解答。<br/>&ndash;&gt;-->\n" +
                "                    <!--&lt;!&ndash;电话：4008-622-333&ndash;&gt;-->\n" +
                "                <!--&lt;!&ndash;</p>&ndash;&gt;-->\n" +
                "            <!--</div>-->\n" +
                "        <!--</td>-->\n" +
                "    <!--</tr>-->\n" +
                "\n" +
                "    <tr>\n" +
                "        <td>\n" +
                "            <div align=\"right\" style=\"margin: 40px;border-top: solid 1px gray\" id=\"bottomTime\">\n" +
                "                <p style=\"margin-right: 20px\">xxx科技有限公司</p>\n" +
                "                <label style=\"margin-right: 20px\">2018年08月30日</label>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "</table>\n" +
                "</body>\n" +
                "</html>";
        MailUtil.send(to ,subject ,content ,isHtml);
    }
}
